<template>
  <div class="count">
    <button @click="handleSub" class="sub">-</button>
    <input @change="handleChange" type="text" :value="value">
    <button @click="handleAdd" class="add">+</button>
  </div>
</template>

<script>
export default {
  data () {
    return {}
  },
  props: {
    value: {
      type: Number,
      default: 1
    }
  },
  methods: {
    handleSub () {
      if (this.value <= 1) return
      this.$emit('input', this.value - 1)
    },
    handleAdd () {
      this.$emit('input', this.value + 1)
    },
    handleChange (event) {
      const num = +event.target.value
      // 输入不合法回退成原来的 value 值
      if (isNaN(num) || num < 1) {
        event.target.value = this.value
        return
      }
      this.$emit('input', num)
    }
  }
}
</script>

<style scoped lang="less">
  .count {
    width: 110px;
    display: flex;
    .sub, .add {
      border: none;
      outline: none;
      width: 30px;
      height: 30px;
    }

    input {
      border: none;
      outline: none;
      background-color: #F0F0F0;
      width: 40px;
      height: 30px;
      margin: 0 5px;
      text-align: center;
    }
  }
</style>
